package com.mpdbailey.cleverdicandroid;

import java.util.ArrayList;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;

import com.pigdogbay.androidutils.utils.ActivityUtils;

public class MainActivity extends FragmentActivity implements Runnable,
		OnClickListener, OnEditorActionListener, IAnagramView,
		OnSharedPreferenceChangeListener
{
	EditText editQuery;
	AnagramPresenter presenter;
	ResultsFragment _ResultsFragment;
	HintsFragment _HintsFragment;

	private ArrayList<String> matchesArray;
	private ArrayAdapter<String> itemAdapter;

	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		((Button) findViewById(R.id.btnSearch)).setOnClickListener(this);
		editQuery = (EditText) findViewById(R.id.editQuery);
		presenter = new AnagramPresenter(this);
		editQuery.setOnEditorActionListener(this);
		_HintsFragment = new HintsFragment();
		_ResultsFragment = new ResultsFragment();
		ReplaceFragment(_HintsFragment);
		matchesArray = new ArrayList<String>();
		itemAdapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_list_item_1, matchesArray);
		_ResultsFragment.setListAdapter(itemAdapter);
		SharedPreferences prefs = PreferenceManager
				.getDefaultSharedPreferences(this);
		prefs.registerOnSharedPreferenceChangeListener(this);

		LoadPreferences(prefs);
		loadDicitionary();
		CheckFirstTime();
		new com.pigdogbay.androidutils.apprate.AppRate(this).setMinDaysUntilPrompt(7)
				.setMinLaunchesUntilPrompt(5).init();

	}

	private void ReplaceFragment(Fragment fragment)
	{
		FragmentManager fragmentManager = getSupportFragmentManager();
		FragmentTransaction fragmentTransaction = fragmentManager
				.beginTransaction();
		fragmentTransaction.replace(R.id.fragmentHolder, fragment);
		fragmentTransaction.commit();
	}

	@Override
	protected void onDestroy()
	{
		super.onDestroy();
		PreferenceManager.getDefaultSharedPreferences(this)
				.unregisterOnSharedPreferenceChangeListener(this);
	}

	private void CheckFirstTime()
	{
		SharedPreferences sharedPrefs = PreferenceManager
				.getDefaultSharedPreferences(this);
		boolean welcomeScreenShown = sharedPrefs.getBoolean(
				StringConstants.PREF_WELCOME_SHOWN, false);
		if (!welcomeScreenShown)
		{
			ShowWelcomeScreen();
			SharedPreferences.Editor editor = sharedPrefs.edit();
			editor.putBoolean(StringConstants.PREF_WELCOME_SHOWN, true);
			editor.commit();
		}
	}

	private void ShowWelcomeScreen()
	{
		String whatsNewTitle = getResources().getString(R.string.welcome_title);
		String whatsNewText = getResources().getString(R.string.welcome_msg);
		new AlertDialog.Builder(this)
				.setIcon(android.R.drawable.ic_dialog_info)
				.setTitle(whatsNewTitle)
				.setMessage(whatsNewText)
				.setPositiveButton(R.string.ok,
						new DialogInterface.OnClickListener()
						{
							public void onClick(DialogInterface dialog,
									int which)
							{
								dialog.dismiss();
							}
						}).show();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu)
	{
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item)
	{
		Intent intent;
		switch (item.getItemId())
		{
		case (R.id.menu_clear):
			presenter.Clear();
			showKeyboard();
			break;
		case (R.id.menu_about):
			intent = new Intent(this, AboutActivity.class);
			startActivity(intent);
			break;
		case (R.id.menu_help):
			intent = new Intent(this, HelpActivity.class);
			startActivity(intent);
			break;
		case (R.id.menu_settings):
			intent = new Intent(this, SettingsActivity.class);
			startActivity(intent);
			break;
		default:
			return false;
		}
		return true;
	}

	public void onClick(View v)
	{
		ReplaceFragment(_ResultsFragment);
		this.presenter.Search();
		try
		{
			InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
			if (imm != null)
			{
				imm.hideSoftInputFromWindow(editQuery.getWindowToken(), 0);
			}
		} catch (Exception e)
		{
		}
	}

	public void setStatus(String status, boolean busy)
	{
		_ResultsFragment.setStatus(status, busy);
	}

	public String getQuery()
	{
		return this.editQuery.getText().toString();
	}

	public void setQuery(String query)
	{
		this.editQuery.setText(query);
	}

	public void setError(String msg)
	{
		editQuery.setError(msg);
	}

	public void addMatch(String match)
	{
		matchesArray.add(match);
		itemAdapter.notifyDataSetChanged();
	}

	public void clearMatches()
	{
		matchesArray.clear();
		itemAdapter.notifyDataSetChanged();
	}

	public String getStringResource(int id)
	{
		return getString(id);
	}

	private void showKeyboard()
	{
		try
		{
			InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
			if (imm != null)
			{
				imm.showSoftInput(editQuery, InputMethodManager.SHOW_IMPLICIT);
			}
		} catch (Exception e)
		{
		}
	}

	public boolean onEditorAction(TextView arg0, int arg1, KeyEvent arg2)
	{
		if (arg1 == EditorInfo.IME_ACTION_DONE)
		{
			onClick(null);
		}
		return false;
	}
	private void loadDicitionary()
	{
		CleverDicApplication app = (CleverDicApplication) getApplication();
		if (app.GetDicitionary() == null)
		{
			// Load dictionary on a worker thread
			Thread t = new Thread(this);
			t.start();
		}
		else
		{
			//dictionary already loaded
			presenter.SetDictionary(app.GetDicitionary());
		}
	}
	/*
	 * (non-Javadoc)
	 * 
	 * @see java.lang.Runnable#run()
	 * 
	 * Dictionary takes around 700ms to load on Nexus 7 and over 2s on my
	 * brothers phone Need to load this on a worker thread in the background to
	 * avoid the application freezing when starting up.
	 */
	public void run()
	{
		try
		{
			CleverDicApplication app = (CleverDicApplication) getApplication();
			app.LoadDictionary();
			presenter.SetDictionary(app.GetDicitionary());
		} catch (Exception e)
		{
			setError(getString(R.string.DictionaryLoadError));
		}
	}

	public void onSharedPreferenceChanged(SharedPreferences prefs, String key)
	{
		LoadPreferences(prefs);
	}

	private void LoadPreferences(SharedPreferences prefs)
	{
		try
		{
			this.presenter.SetFindSubAngrams(prefs.getBoolean(
					getString(R.string.settings_show_subanagrams_pref_key),
					true));
			int limit = Integer.parseInt(prefs.getString(
					getString(R.string.settings_result_limit_pref_key),
					getString(R.string.settings_result_limit_default)));
			this.presenter.SetResultLimit(limit);
			boolean autoRotate = prefs.getBoolean(
					getString(R.string.settings_autorotate_pref_key), false);
			ActivityUtils.enableOrientation(this, autoRotate);

		} catch (Exception e)
		{
			Log.v("CleverDic", "Unable to load preferences");
		}

	}

}
